package vikaa.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import vikaa.adapter.PhotoAdapter;
import vikaa.bean.photoitem;
import vikaa.timelinepackage.TimelineGallery;
import vikaa.tools.FileUtils;
import vikaa.wowo.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ChoosePhotoList extends Activity{
	private LinearLayout backBtn;
	private ImageView submitBtn;
	private GridView gridView_check;	
	private ArrayList<String> list = new ArrayList<String>();
	private String sid;
	private PhotoAdapter adapter;
	ArrayList<photoitem> mSongs = new ArrayList<photoitem>();
	private LinearLayout header;
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photolist);
		header = (LinearLayout)findViewById(R.id.header);
		Intent i = getIntent();
		sid = TimelineGallery.space_id;
		initview();
		findimgpath();
	}
	public void initview(){
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new clickListener());
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(new clickListener());
        gridView_check = (GridView) findViewById(R.id.gridview_check);
        adapter = new PhotoAdapter(this, gridView_check,mSongs);
        gridView_check.setAdapter(adapter);
        gridView_check.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				// TODO Auto-generated method stub
				adapter.changeState(position,view);
				boolean isadd = false;
				String Imagepath = mSongs.get(position).getPath();
				if(list.size()>0){
					for(int i=0;i<list.size();i++){
						if(list.get(i).equals(Imagepath)){
							list.remove(i);
							isadd = false;
							break;
						}
						isadd = true;
					}
					if(isadd)list.add(Imagepath);
				}
				else 
					list.add(Imagepath);
			}
		});
        //DialogService.showProgressDialog(ChoosePhotoList.this, getString(R.string.get_photo));
	}
	class clickListener implements OnClickListener{
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch(v.getId()){
			case R.id.backBtn:
				finish();
				break;
			case R.id.submitBtn:
				Log.i("path", list.size()+"");
				if(list.size()>0){
					Intent i = new Intent(ChoosePhotoList.this,ChoosePhotoUpload.class);
					Bundle b = new Bundle();
					b.putString("sid", sid);
					b.putStringArrayList("pathlist", list);
					i.putExtras(b);
					startActivity(i);
					finish();
				}
				else
					Log.i("p", "no");
				break;
			}
		}
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case 1:
				if(msg.obj != null){
					List<photoitem> strings = (List<photoitem>) msg.obj;
					if(!strings.isEmpty()){
						adapter.notifyDataSetChanged();
						header.setVisibility(View.GONE);
						//DialogService.closeProgressDialog();
						//list.clear();
					}
				}
				break;
			case 0:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				TextView tv1 = (TextView)findViewById(R.id.emptyTv);
				TextView tv2 = (TextView)findViewById(R.id.emptydivider);
				tv1.setVisibility(View.VISIBLE);
				tv2.setVisibility(View.VISIBLE);
				break;
			}
		}
    };
    public void findimgpath(){
    	new Thread(new Runnable() {
			public void run() {
				/*boolean got = false;
				ContentResolver cr = getContentResolver();
				if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
					Cursor cursor = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,null, null, null, null);
			    	if(cursor.moveToFirst()){
			    		for(int i=0;i<cursor.getCount();i++){
			    			String imgID = cursor.getString(cursor.getColumnIndex(Thumbnails.IMAGE_ID));//cursor.getString(1);
			    			String imgPath = cursor.getString(cursor.getColumnIndex(Thumbnails.DATA));
			    			cursor.moveToNext();
			    			list.add(imgID);
			    			adapter.addPath(imgID,imgPath,false);
			    		}
			    		got = true;
			    	}
				}
				Cursor cursor = cr.query(MediaStore.Images.Thumbnails.INTERNAL_CONTENT_URI,null, null, null, null);
		    	if(cursor.moveToFirst()){
		    		for(int i=0;i<cursor.getCount();i++){
		    			String imgID = cursor.getString(cursor.getColumnIndex(Thumbnails.IMAGE_ID));//cursor.getString(1);
		    			String imgPath = cursor.getString(cursor.getColumnIndex(Thumbnails.DATA));
		    			cursor.moveToNext();
		    			list.add(imgID);
		    			adapter.addPath(imgID,imgPath,false);
		    		}
		    		got = true;
		    	}
		    	if(got){
		    		Message msg = mhandler.obtainMessage(1);
		    		msg.obj = list;
		    		msg.sendToTarget();
		    	}
		    	else{
		    		Message msg = mhandler.obtainMessage(0);
					msg.sendToTarget();
		    	}*/
				TraversalSDcard(FileUtils.getSDCardRoot());
				Message msg = mhandler.obtainMessage(1);
	    		msg.obj = mSongs;
	    		msg.sendToTarget();
			}
    	}).start();
    }
    /**
	 * 遍历sdcard中的像素在400以上的图片文件夹
	 * @param path
	 */
	public  void TraversalSDcard(String path) {
        String paths = path + "/";
        File file = new File(paths);
        File[] filelist = file.listFiles();
        if (filelist != null) {
            for (int i = 0; i < filelist.length; i++) {
                if (filelist != null) {
                    File g = new File(filelist[i].getPath());
                    if (g.isDirectory() && !g.isHidden() ) {
                        TraversalSDcard(g.getPath());

                    } else if (g.getName().endsWith(".jpg") || g.getName().endsWith(".jpeg")) {
                    	Options options = new Options();
                		options.inJustDecodeBounds = true;
                		BitmapFactory.decodeFile(g.getPath(), options);
                		if(options.outWidth > 400 && options.outHeight >400){
                			photoitem ti = new photoitem();
                			ti.setPath(g.getAbsolutePath());
                			ti.setIsselected(false);
                			mSongs.add(ti);
                		}
                    }
                }
            }
        }
	 }
}
